#!/bin/env bash
LIBC_PATH=$(ldconfig -p | grep libc.so.6 | awk '{print $4}')
LIBC_VERSION=$($LIBC_PATH | awk '/GNU C Library/{print $NF}')
REQUIRED_VERSION="2.34"
if [[ "$(printf '%s\n' "$REQUIRED_VERSION" "$LIBC_VERSION" | sort -V | head -n1)" != "$REQUIRED_VERSION" ]]; then
    echo -e "\e[31m警告：当前glibc版本为 $LIBC_VERSION，低于所需的 $REQUIRED_VERSION 版本。需要人工介入！\e[0m"
    exit 1
fi

install() {
    pkg=$(command -v apt yum pacman 2>/dev/null)
    case $pkg in
        */apt)  apt-get install -y ${1} ;;
        */yum)  yum install -y ${1} ;;
        */pacman) pacman -Syu --noconfirm ${1} ;;
        *) echo "code 45"; exit 1 ;;
    esac
}
download() {
    if [ -f "${1}/${2}" ]; then
        local_sha256=$(sha256sum "${1}/${2}" | awk '{print $1}')
        remote_sha256=$(curl -sL "https://yxyos.cn/pan/yunzai/${3}/sha256.txt" | grep ${2} | awk '{print $1}')
        if [[ "$local_sha256" != "$remote_sha256" ]]; then
            rm -f "${1}/${2}"
        fi
    fi
    if ! command -v wget &> /dev/null; then
        echo "wget 未安装，正在安装..."
        install wget
        if [ $? -ne 0 ]; then
            echo "安装失败"
            return 1
        fi
    fi

    wget -c https://yxyos.cn/pan/yunzai/${3}/${2} -P ${1}
    if [ $? -ne 0 ]; then
        echo "下载失败"
        rm -f ${1}/${2}
        return 1
    fi
}
mkdir -p ${DIR:=/root/bot}
FILE="env-"$(uname -m)".tar.gz"
download $DIR $FILE ${VER:=latest}
if [ $? -eq 0 ]; then
    if [ ! -d $DIR/env ]; then
        tar -xzf $DIR/$FILE -C $DIR
        if [ $? -ne 0 ]; then
            echo "解压失败"
            exit 1
        fi
    fi
    [ -d $DIR/env ] && rm -f $DIR/$FILE
        apt-get install lsb-release -y >/dev/null 2>&1
        source /usr/lib/os-release
    if [ "$(lsb_release -si)" = "Ubuntu" ]  || [[ "$NAME" = "Ubuntu" ]]; then
        install -y chromium-browser
    else
        install chromium
fi
    echo "环境安装完成"
    CMD="source $DIR/env/env.sh"
    [ ! -f ~/.bashrc ] && touch ~/.bashrc
    if ! grep -Fxq "$CMD" ~/.bashrc; then
        echo -e "\n$CMD" >> ~/.bashrc
        exec bash -c "$CMD; exec bash"
    fi
fi
